<template>
  <el-container class="app-container">
    <el-collapse @change="handleCollapseChange" v-model="collapseActiveName">
      <el-collapse-item :title="collapseTitle" name="1">
        <el-tabs type="border-card">
          <el-form :model="pageInfo" ref="form" label-width="130px" size="medium">
            <el-row>
              <el-col :span="9" :offset="0">
                <el-form-item prop="name" label="办公空间名称：">
                  <el-input v-model.trim='pageInfo.name' placeholder="请输入名称搜索"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6" :offset="1">
                <el-button type="primary" icon="el-icon-search" @click='getData(1)'>搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-tabs>
      </el-collapse-item>
    </el-collapse>
    <el-header class="m-t-20">
      <el-button type="primary" icon="el-icon-plus" @click="addOne">办公空间</el-button>
    </el-header>

    <!--表格-->
    <table-view
      :editBtnMap="true"
      :editBtnMapList="editBtnMapList"
      :columns="tableContent"
      :pageList="columnData"
      @edit-btnclick="editBtnClick"
      :templateDiv="{itemMessage:true,operation:true,remark:true}"
    >
      <template slot="itemMessage" slot-scope="scope">
        <el-row class="table-item-message">
          <div class="item-image"><img :src="scope.row.areaPic" alt=""></div>
          <div class="item-mess">
            <p class="item-title">{{scope.row.areaName}}</p>
            <p class="item-title">{{scope.row.addressName}}-{{scope.row.address}}</p>
          </div>
        </el-row>
      </template>
      <template slot="remark" slot-scope="scope">
        <el-popover
          v-if="scope.row.remark && scope.row.remark.length>16"
          placement="top-start"
          width="200"
          trigger="hover"
          :content="scope.row.remark">
          <div slot="reference" style="width: 150px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap">{{scope.row.remark}}</div>
        </el-popover>
        <span v-else>
          {{scope.row.remark}}
        </span>
      </template>
    </table-view>

    <!--分页-->
    <pagination-view :pagesize="pageInfo.pageSize"
                     :currentPage="pageInfo.pageNumber"
                     :total="total"
                     @size-change="sizeChange"
                     @current-change="pageChange"
    ></pagination-view>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%"
               :destroy-on-close="true" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="width: 90%">
        <el-form-item prop="areaPic" label="办公空间图片:">
          <img-upload class="form-pic" @upload-callback="handleUpload(arguments[0],{name:'areaPic'})"
                      :imageUrl="form.areaPic" uploadFrom="operation"></img-upload>
          <!--          <span class="form-item-tip">建议尺寸690*276，只能上传jpg/png格式文件，文件不能超过50kb</span>-->
        </el-form-item>
        <el-form-item prop="areaName" label="办公空间名称:">
          <el-input v-model.trim="form.areaName"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="map地址:">
          <el-input style="width: 70%;margin-right: 8px" v-model.trim="form.addressName" placeholder="地址名称"></el-input>
          <el-button type="primary" @click="getMapPoint">地图取点</el-button>
          <el-input v-model.trim="form.address" placeholder="详细地址" class="m-t-10"></el-input>
        </el-form-item>

        <el-form-item prop="remark" label="空间备注:">
          <el-input v-model.trim="form.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="status" v-if="dialogType!=='add'">
          <el-switch
            v-model="form.status"
            active-text="正常"
            inactive-text="停用">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="dialogView" width="60%"
               :destroy-on-close="true" :before-close="handleClose">
      <el-row class="view-area">
        <el-col :span='8' offset="1">
          <p>空间ID:{{form.id}}</p>
          <p>办公空间图片: <img :src="form.areaPic" alt="" style="width: 100px;vertical-align: top"></p>
          <p>办公空间名称:{{form.areaName}}</p>
          <p>map地址:{{form.addressName}}-{{form.address}}</p>
          <p>状态:{{form.status?'开启':'停用'}}</p>
          <p>空间备注:{{form.remark}}</p>
        </el-col>
        <el-col :span='8' offset="3">
          <h4>操作记录</h4>
          <p>创建:</p>
          <p>
            {{form.createLog.length?form.createLog[0].createdTime:''}}({{form.createLog.length?form.createLog[0].operatorName:''}})</p>
          <el-row v-if="form.editLog.length">
            <p>编辑:</p>
            <p v-for="(item,i) in form.editLog" :key="i">{{item.operatorName}}({{item.operatorName}})</p>
            <p>空间备注:{{form.remark}}</p>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>

    <el-footer></el-footer>
  </el-container>
</template>

<script>
  import TableView from '@/components/TableView'
  import ImgUpload from '@/components/ImgUpload'

  import PaginationView from '@/components/PaginationView'
  import * as pageApi from '@/api/spaceBusiness/spaceManage'

  export default {
    name: 'list',
    components: {
      TableView,
      PaginationView,
      ImgUpload
    },
    data() {
      return {
        dialogView: false,
        dialogTitle: '添加',
        dialogVisible: false,
        dialogType: 'add',
        tableContent: [{
          field: 'itemMessage',
          label: '名称',
          width: 200
        }, {
          field: 'roomTotalArea',
          label: '房源面积',
          sortable: true
        }, {
          field: 'investmentArea',
          label: '可招商面积',
          sortable: true
        }, {
          field: 'roomTotalNum',
          label: '房源数量',
          sortable: true
        }, {
          field: 'investmentRoomNum',
          label: '可招商房源',
          sortable: true
        }, {
          field: 'rentalRate',
          label: '出租率',
          sortable: true
        }, {
          field: 'averagePrice',
          label: '在租均价',
          sortable: true
        }, {
          field: 'remark',
          label: '备注',
          width:150
        }],
        columnData: [],
        editBtnMapList: ['update', 'view', 'delete'],  //自定义的按钮内容
        customWidth: '',
        pageInfo: {
          name: '',
          pageNumber: 1,
          pageSize: 20,
        },
        total: 0,
        form: {
          areaPic: '',
          areaName: '',
          address: '',
          remark: '',
          createLog: [],
          editLog: [],
          status: true
        },
        rules: {
          areaName: [
            {required: true, trigger: 'blur', message: '名称不能为空'},
          ],
          address: [
            {required: true, trigger: 'blur', message: '地址不能为空'},
          ],
          areaPic: [{required: true, trigger: 'change', message: '请上传图片'}],
          // sort: [{required: true, trigger: 'blur', message: '请填写排序'}],
          // enable: [{required: true, trigger: 'change', message: '请选择套餐状态'}],
          // tag: [{min: 1, max: 4, trigger: 'blur', message: '长度不能超过4个汉字'}],
        }
      }
    },
    watch: {},
    methods: {
      resetSearch() {
        this.pageInfo = {
          name: '',
          pageNumber: 1,
          pageSize: 20,
        }
        this.getData()
      },
      handleUpload(url, obj) {
        this.$set(this.form, obj.name, url)
      },
      pars(param, key, encode) {
        if (param == null) return '';
        var arr = [];
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
          arr.push(key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param));
        } else {
          for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            arr.push(pars(param[i], k, encode));
          }
        }
        return arr.join("&");
      },
      getMapPoint() {

        localStorage.setItem('formSpace', JSON.stringify(this.form));
        window.location.href = `https://3gimg.qq.com/lightmap/components/locationPicker2/index.html?search=1&type=0&key=7JNBZ-7SS3F-CDYJB-JL5R4-I5GME-I6FL2&referer=myapp&backurl=${encodeURIComponent(location.origin + '/spaceBusiness/spaceManageList?show=true&dialogTitle=' + this.dialogTitle)}`
      },
      addOne() {
        this.form = {
          areaPic: '',
          areaName: '',
          address: '',
          remark: '',
          createLog: [],
          editLog: [],
        }
        this.dialogVisible = true
        this.dialogTitle = '添加'
      },

      changeUserStatus: function (id, enable) {
        pageApi.changeEnable(id, enable).then((res) => {
          this.handleMessage(res)
          if (res.code === '200') this.getData()
        })
      },
      onSubmit() {
        let form = this.form
        let dialogType = this.dialogType
        this.$refs['form'].validate((valid) => {
          if (valid) {
            switch (dialogType) {
              case 'add':
                this.dialogTitle = '添加'
                pageApi.create(form).then(res => {
                  this.handleRes(res)
                  this.$router.replace({name: 'spaceManageList'})
                })
                localStorage.removeItem('formSpace')
                break
              case 'update':
                this.dialogTitle = '编辑'
                pageApi.update(form.id, form).then(res => {
                  this.handleRes(res)
                  this.$router.replace({name: 'spaceManageList'})
                })
                localStorage.removeItem('formSpace')
                break
            }
          }
        })
      },
      handleRes(res) {
        this.handleMessage(res)
        if (res.code === '200') {
          this.dialogVisible = false
          this.getData()
        }
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val
        this.getData()
      },
      // page变化函数
      pageChange(val) {
        // debugger
        this.pageInfo.pageNumber = val
        this.getData()
      },
      editBtnClick(val, index, type) {
        switch (type) {
          case 'view':
            pageApi.getById(val.id).then(res => {
              this.form = Object.assign({}, this.form, res.body)
            })
            this.dialogView = true
            break
          case 'update':
            pageApi.getById(val.id).then(res => {
              this.form = Object.assign({}, this.form, res.body)
            })
            this.dialogType = type
            this.dialogVisible = true
            break
          case 'delete':
            pageApi.deleteIt(val.id).then(res => {
              if (res.code === '200') {
                this.handleRes(res)
                this.getData()
              }
            })
            break
        }
      },
      //拉取列表
      getData(current) {
        this.pageInfo.pageNumber = current ? current : this.pageInfo.pageNumber
        pageApi.getList(this.pageInfo).then(res => {
          this.columnData = res.body.objects
          this.total = Number(res.body.recordTotal)

          this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
        })
      },
      handleClose(done) {
        let resetForm = {
          areaPic: '',
          areaName: '',
          address: '',
          addressName:'',
          remark: '',
        }
        this.form = Object.assign({}, this.form, resetForm)
        done()
      }

    },
    mounted() {
      // addr: "浙江省杭州市萧山区金惠路685号"
      // city: "杭州市"
      // latng: "30.185281,120.26323"
      // module: "locationPicker"
      // name: "杭州市萧山区委杭州市萧山区人民政府信访局"
      // show: "true"
      let {addr, latng, name, show, dialogTitle} = this.$route.query
      let formSpace = localStorage.getItem('formSpace');
      formSpace = JSON.parse(formSpace)
      console.log(formSpace);
      this.form = Object.assign({},this.form, formSpace)
      this.form.address = addr
      this.form.addressName = name
      this.dialogTitle = dialogTitle
      if (show) {
        this.dialogVisible = true
      }
      this.getData()
    }
  }
</script>

<style lang="scss" scoped>
  .view-area {
    p {
      margin-bottom: 20px
    }
  }
</style>
